package com.lzx.mumianaicodegenerator.manager;

import com.lzx.mumianaicodegenerator.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.File;
@Component
@Slf4j
public class CosManager {
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private COSClient cosClient;
    /**
     * 上传对象
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectResult = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        return cosClient.putObject(putObjectResult);
    }

    /**
     * 上传文件到COS并返回访问URL
     */
    public String uploadFile(String key,File file) {
        PutObjectResult result = putObject(key, file);
        if (result != null) {
            String url = String.format("%s%s", cosClientConfig.getHost(), key);
            log.info("上传文件成功，{} -> {}", file.getName(),url);
            return url;
        }else {
            log.error("上传文件失败，返回结果为空");
            return null;
        }
    }
}
